﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using System.Diagnostics.CodeAnalysis;

namespace Steve.UI
{
    public sealed class PermanentRedirectResult : ActionResult
    {
        [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")]
        public string Url { get; set; }

        [SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads")]
        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")]
        public PermanentRedirectResult(string url)
        {
            if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException("url");

            this.Url = url;
        }

        public PermanentRedirectResult(Uri url)
        {
            if (url == null) throw new ArgumentNullException("url");

            this.Url = url.ToString();
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (context.IsChildAction)
            {
                throw new InvalidOperationException("Cannot redirect from a child action.");
            }

            string url = UrlHelper.GenerateContentUrl(this.Url, context.HttpContext);

            context.Controller.TempData.Keep();
            context.HttpContext.Response.StatusCode = 301;
            context.HttpContext.Response.RedirectLocation = url;
        }
    }
}
